<!DOCTYPE html>












  


<html class="theme-next pisces use-motion" lang="zh-CN">
<head><meta name="generator" content="Hexo 3.9.0">
  <meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=2">
<meta name="theme-color" content="#222">












  <link rel="apple-touch-icon" sizes="180x180" href="/images/apple-touch-icon-next.png?v=7.2.0">


  <link rel="icon" type="image/png" sizes="32x32" href="/images/favicon-32x32-next.png?v=7.2.0">


  <link rel="icon" type="image/png" sizes="16x16" href="/images/favicon-16x16-next.png?v=7.2.0">


  <link rel="mask-icon" href="/images/logo.svg?v=7.2.0" color="#222">






<link rel="stylesheet" href="/css/main.css?v=7.2.0">






<link rel="stylesheet" href="/lib/font-awesome/css/font-awesome.min.css?v=4.7.0">






  
  
  <link rel="stylesheet" href="/lib/fancybox/source/jquery.fancybox.css">



<script id="hexo.configurations">
  var NexT = window.NexT || {};
  var CONFIG = {
    root: '/',
    scheme: 'Pisces',
    version: '7.2.0',
    sidebar: {"position":"left","display":"post","offset":12,"onmobile":false},
    back2top: {"enable":true,"sidebar":false,"scrollpercent":true},
    copycode: {"enable":true,"show_result":true,"style":null},
    fancybox: true,
    mediumzoom: false,
    lazyload: false,
    pangu: false,
    algolia: {
      applicationID: '',
      apiKey: '',
      indexName: '',
      hits: {"per_page":10},
      labels: {"input_placeholder":"Search for Posts","hits_empty":"We didn't find any results for the search: ${query}","hits_stats":"${hits} results found in ${time} ms"}
    },
    localsearch: {"enable":true,"trigger":"auto","top_n_per_article":1,"unescape":false,"preload":false},
    search: {
      root: '/',
      path: 'search.xml'
    },
    tabs: true,
    motion: {"enable":true,"async":false,"transition":{"post_block":"fadeIn","post_header":"slideDownIn","post_body":"slideDownIn","coll_header":"slideLeftIn","sidebar":"slideUpIn"}},
    translation: {
      copy_button: '复制',
      copy_success: '复制成功',
      copy_failure: '复制失败'
    }
  };
</script>

  <meta name="description" content="What WebAssembly ? WebAssembly简称WASM，是一种以安全有效的方式运行便携式程序的新技术，主要针对Web平台。与ASM.js类似，WASM的目标是低级别的抽象，适合作为更高级别程序的中间表示 - 即WebAssembly代码旨在由编译器生成而不是由人类编写。在W3C社区组包括来自最大的网络浏览器的公司，包括谷歌，微软，苹果和Mozilla做这件事，而令人兴奋的代表。">
<meta name="keywords" content="webAssembly">
<meta property="og:type" content="article">
<meta property="og:title" content="webAssembly">
<meta property="og:url" content="https://blog.youngzk.com/posts/7f98c2be/index.html">
<meta property="og:site_name" content="Muniz Blog">
<meta property="og:description" content="What WebAssembly ? WebAssembly简称WASM，是一种以安全有效的方式运行便携式程序的新技术，主要针对Web平台。与ASM.js类似，WASM的目标是低级别的抽象，适合作为更高级别程序的中间表示 - 即WebAssembly代码旨在由编译器生成而不是由人类编写。在W3C社区组包括来自最大的网络浏览器的公司，包括谷歌，微软，苹果和Mozilla做这件事，而令人兴奋的代表。">
<meta property="og:locale" content="zh-CN">
<meta property="og:updated_time" content="2019-07-28T05:22:54.721Z">
<meta name="twitter:card" content="summary">
<meta name="twitter:title" content="webAssembly">
<meta name="twitter:description" content="What WebAssembly ? WebAssembly简称WASM，是一种以安全有效的方式运行便携式程序的新技术，主要针对Web平台。与ASM.js类似，WASM的目标是低级别的抽象，适合作为更高级别程序的中间表示 - 即WebAssembly代码旨在由编译器生成而不是由人类编写。在W3C社区组包括来自最大的网络浏览器的公司，包括谷歌，微软，苹果和Mozilla做这件事，而令人兴奋的代表。">





  
  
  <link rel="canonical" href="https://blog.youngzk.com/posts/7f98c2be/">



<script id="page.configurations">
  CONFIG.page = {
    sidebar: "",
  };
</script>

  
  <title>webAssembly | Muniz Blog</title>
  






  <script>
    var _hmt = _hmt || [];
    (function() {
      var hm = document.createElement("script");
      hm.src = "https://hm.baidu.com/hm.js?502753d7b083822cd84ffc61132a5ac4";
      var s = document.getElementsByTagName("script")[0];
      s.parentNode.insertBefore(hm, s);
    })();
  </script>







  <noscript>
  <style>
  .use-motion .motion-element,
  .use-motion .brand,
  .use-motion .menu-item,
  .sidebar-inner,
  .use-motion .post-block,
  .use-motion .pagination,
  .use-motion .comments,
  .use-motion .post-header,
  .use-motion .post-body,
  .use-motion .collection-title { opacity: initial; }

  .use-motion .logo,
  .use-motion .site-title,
  .use-motion .site-subtitle {
    opacity: initial;
    top: initial;
  }

  .use-motion .logo-line-before i { left: initial; }
  .use-motion .logo-line-after i { right: initial; }
  </style>
</noscript>

</head>

<body itemscope itemtype="http://schema.org/WebPage" lang="zh-CN">

  
  
    
  

  <div class="container sidebar-position-left page-post-detail">
    <div class="headband"></div>

    <header id="header" class="header" itemscope itemtype="http://schema.org/WPHeader">
      <div class="header-inner"><div class="site-brand-wrapper">
  <div class="site-meta">
    

    <div class="custom-logo-site-title">
      <a href="/" class="brand" rel="start">
        <span class="logo-line-before"><i></i></span>
        <span class="site-title">Muniz Blog</span>
        <span class="logo-line-after"><i></i></span>
      </a>
    </div>
    
    
  </div>

  <div class="site-nav-toggle">
    <button aria-label="切换导航栏">
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
    </button>
  </div>
</div>



<nav class="site-nav">
  
    <ul id="menu" class="menu">
      
        
        
        
          
          <li class="menu-item menu-item-home">

    
    
      
    

    

    <a href="/" rel="section"><i class="menu-item-icon fa fa-fw fa-home"></i> <br>首页</a>

  </li>
        
        
        
          
          <li class="menu-item menu-item-books">

    
    
      
    

    

    <a href="/books" rel="section"><i class="menu-item-icon fa fa-fw fa-question-circle"></i> <br>阅读</a>

  </li>
        
        
        
          
          <li class="menu-item menu-item-tags">

    
    
      
    

    

    <a href="/tags/" rel="section"><i class="menu-item-icon fa fa-fw fa-tags"></i> <br>标签</a>

  </li>
        
        
        
          
          <li class="menu-item menu-item-categories">

    
    
      
    

    

    <a href="/categories/" rel="section"><i class="menu-item-icon fa fa-fw fa-th"></i> <br>分类</a>

  </li>
        
        
        
          
          <li class="menu-item menu-item-archives">

    
    
      
    

    

    <a href="/archives/" rel="section"><i class="menu-item-icon fa fa-fw fa-archive"></i> <br>归档</a>

  </li>

      
      
        <li class="menu-item menu-item-search">
          <a href="javascript:;" class="popup-trigger">
          
            <i class="menu-item-icon fa fa-search fa-fw"></i> <br>搜索</a>
        </li>
      
    </ul>
  

  

  
    <div class="site-search">
      
  <div class="popup search-popup local-search-popup">
  <div class="local-search-header clearfix">
    <span class="search-icon">
      <i class="fa fa-search"></i>
    </span>
    <span class="popup-btn-close">
      <i class="fa fa-times-circle"></i>
    </span>
    <div class="local-search-input-wrapper">
      <input autocomplete="off" placeholder="搜索..." spellcheck="false" type="text" id="local-search-input">
    </div>
  </div>
  <div id="local-search-result"></div>
</div>



    </div>
  
</nav>



</div>
    </header>

    


    <main id="main" class="main">
      <div class="main-inner">
        <div class="content-wrap">
          
            

          
          <div id="content" class="content">
            

  <div id="posts" class="posts-expand">
      

  
  
  

  

  <article class="post post-type-normal" itemscope itemtype="http://schema.org/Article">
  
  
  
  <div class="post-block">
    <link itemprop="mainEntityOfPage" href="https://blog.youngzk.com/posts/7f98c2be/">

    <span hidden itemprop="author" itemscope itemtype="http://schema.org/Person">
      <meta itemprop="name" content="修心">
      <meta itemprop="description" content="修不被别人影响的心，修不被自己控制的心，修不被别人诱惑的心。">
      <meta itemprop="image" content="/images/avatar.jpg">
    </span>

    <span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
      <meta itemprop="name" content="Muniz Blog">
    </span>

    
      <header class="post-header">

        
        
          <h1 class="post-title" itemprop="name headline">webAssembly

              
            
          </h1>
        

        <div class="post-meta">

          
          
          

          
            <span class="post-meta-item">
              <span class="post-meta-item-icon">
                <i class="fa fa-calendar-o"></i>
              </span>
              
                <span class="post-meta-item-text">发表于</span>
              

              
                
              

              <time title="创建时间：2018-08-26 09:37:54" itemprop="dateCreated datePublished" datetime="2018-08-26T09:37:54+08:00">2018-08-26</time>
            </span>
          

          
            

            
              <span class="post-meta-item">
                <span class="post-meta-item-icon">
                  <i class="fa fa-calendar-check-o"></i>
                </span>
                
                  <span class="post-meta-item-text">更新于</span>
                
                <time title="修改时间：2019-07-28 13:22:54" itemprop="dateModified" datetime="2019-07-28T13:22:54+08:00">2019-07-28</time>
              </span>
            
          

          

          
          

          
            <span class="post-meta-item">
              <span class="post-meta-item-icon">
                <i class="fa fa-eye"></i>
                 阅读次数： 
                <span class="busuanzi-value" id="busuanzi_value_page_pv"></span>
              </span>
            </span>
          

          

          <br>
          

          

          

        </div>
      </header>
    

    
    
    
    <div class="post-body" itemprop="articleBody">

      
      

      
        <h2 id="What-WebAssembly"><a href="#What-WebAssembly" class="headerlink" title="What WebAssembly ?"></a>What WebAssembly ?</h2><ul>
<li><p>WebAssembly简称WASM，是一种以安全有效的方式运行便携式程序的新技术，主要针对Web平台。与ASM.js类似，WASM的目标是低级别的抽象，适合作为更高级别程序的中间表示 - 即WebAssembly代码旨在由编译器生成而不是由人类编写。在W3C社区组包括来自最大的网络浏览器的公司，包括谷歌，微软，苹果和Mozilla做这件事，而令人兴奋的代表。</p>
</li>
<li><p>WebAssembly是一种新的适合于编译到Web的，可移植的，大小和加载时间高效的格式，是一种新的字节码格式。它的缩写是”.wasm”，.wasm 为文件名后缀，是一种新的底层安全的“二进制”语法。它被定义为“精简、加载时间短的格式和执行模型”，并且被设计为Web 多编程语言目标文件格式。<br>这意味着浏览器端的性能会得到极大提升，它也使得我们能够实现一个底层构建模块的集合.</p>
</li>
</ul>
<a id="more"></a>

<h2 id="webAssembly的优势"><a href="#webAssembly的优势" class="headerlink" title="webAssembly的优势"></a>webAssembly的优势</h2><p>webassembly相较于asm.js的优势主要是涉及到性能方面。根据WebAssembly FAQ的描述：在移动设备上，对于很大的代码库，asm.js仅仅解析就需要花费20-40秒，而实验显示WebAssembly的加载速度比asm.js快了20倍，这主要是因为相比解析 asm.js 代码，JavaScript 引擎破译二进制格式的速度要快得多。</p>
<p>主流的浏览器目前均支持webAssembly。</p>
<ul>
<li>Safari 支持 WebAssembly的第一个版本是 11</li>
<li>Edge 支持 WebAssembly的第一个版本是 16</li>
<li>Firefox 支持 WebAssembly的第一个版本是 52</li>
<li>chrome 支持 WebAssembly的第一个版本是 57</li>
</ul>
<p>使用WebAssembly，我们可以在浏览器中运行一些高性能、低级别的编程语言，可用它将大型的C和C++代码库比如游戏、物理引擎甚至是桌面应用程序导入Web平台。</p>
<h2 id="开发前准备工作"><a href="#开发前准备工作" class="headerlink" title="开发前准备工作"></a>开发前准备工作</h2><h3 id="操作系统"><a href="#操作系统" class="headerlink" title="操作系统"></a>操作系统</h3><blockquote>
<p>MAC系统</p>
</blockquote>
<h3 id="安装工具"><a href="#安装工具" class="headerlink" title="安装工具"></a>安装工具</h3><blockquote>
<p>git 、node 、python 、cmake、emsdk</p>
</blockquote>
<h4 id="git"><a href="#git" class="headerlink" title="git"></a>git</h4><p>已经默认装</p>
<h4 id="node"><a href="#node" class="headerlink" title="node"></a>node</h4><h4 id="python"><a href="#python" class="headerlink" title="python"></a>python</h4><p>官网：<a href="https://www.python.org" target="_blank" rel="noopener">https://www.python.org</a><br>下载地址：<a href="https://www.python.org/ftp/python/3.7.0/python-3.7.0-macosx10.9.pkg" target="_blank" rel="noopener">https://www.python.org/ftp/python/3.7.0/python-3.7.0-macosx10.9.pkg</a></p>
<h4 id="cmake"><a href="#cmake" class="headerlink" title="cmake"></a>cmake</h4><p> 官网：<a href="http://www.cmake.org" target="_blank" rel="noopener">http://www.cmake.org</a><br> 下载地址：<a href="https://cmake.org/files/v3.12/cmake-3.12.1-Darwin-x86_64.dmg" target="_blank" rel="noopener">https://cmake.org/files/v3.12/cmake-3.12.1-Darwin-x86_64.dmg</a></p>
<p> 为了可以在命令行中使用，需要执行一下命令。<br> sudo “/Applications/CMake.app/Contents/bin/cmake-gui” –install</p>
<h4 id="emsdk"><a href="#emsdk" class="headerlink" title="emsdk"></a>emsdk</h4><p>Emscripten 的底层是 LLVM 编译器，理论上任何可以生成 LLVM IR（Intermediate Representation）的语言，都可以编译生成 asm.js。 但是实际上，Emscripten 几乎只用于将 C / C++ 代码编译生成 asm.js。</p>
<blockquote>
<p>** C/C++ ** ⇒ ** LLVM ** ==&gt; ** LLVM IR ** ⇒ ** Emscripten ** ⇒ ** asm.js **</p>
</blockquote>
<figure class="highlight bash"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br></pre></td><td class="code"><pre><span class="line">git <span class="built_in">clone</span> https://github.com/juj/emsdk.git</span><br><span class="line"></span><br><span class="line"><span class="built_in">cd</span> emsdk</span><br><span class="line"></span><br><span class="line">./emsdk update</span><br><span class="line">./emsdk install latest</span><br><span class="line">./emsdk activate latest</span><br><span class="line"></span><br><span class="line"><span class="built_in">source</span> ./emsdk_env.sh</span><br></pre></td></tr></table></figure>

<h3 id="浏览器支持"><a href="#浏览器支持" class="headerlink" title="浏览器支持"></a>浏览器支持</h3><blockquote>
<p>Chrome: 打开 chrome://flags/#enable-webassembly，选择 enable。<br>Firefox: 打开 about:config 将 javascript.options.wasm 设置为 true。</p>
</blockquote>
<h2 id="开始编程"><a href="#开始编程" class="headerlink" title="开始编程"></a>开始编程</h2><h3 id="编写C代码"><a href="#编写C代码" class="headerlink" title="编写C代码"></a>编写C代码</h3><p>创建** example.c ** 文件，并写入如下代码</p>
<figure class="highlight c"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">// example.c</span></span><br><span class="line"></span><br><span class="line"><span class="function"><span class="keyword">float</span> <span class="title">add</span><span class="params">(<span class="keyword">float</span> a,<span class="keyword">float</span> b)</span></span>&#123;</span><br><span class="line"><span class="keyword">return</span> a+b;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<h3 id="编译出wasm"><a href="#编译出wasm" class="headerlink" title="编译出wasm"></a>编译出wasm</h3><p>** bash 执行命令： **</p>
<figure class="highlight bash"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">emcc -s EXPORTED_FUNCTIONS=<span class="string">"['_add]"</span> example.c -s WASM=1 -s SIDE_MODULE=1 -s BINARYEN_ASYNC_COMPILATION=0 -o example.wasm</span><br></pre></td></tr></table></figure>

<h3 id="调用wasm"><a href="#调用wasm" class="headerlink" title="调用wasm"></a>调用wasm</h3><blockquote>
<p>js调用wasm中导出的module</p>
</blockquote>
<p>** loader模块编写 **</p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">loadWebAssembly</span>(<span class="params">path, imports = &#123;&#125;</span>) </span>&#123;</span><br><span class="line">  <span class="keyword">return</span> fetch(path)</span><br><span class="line">    .then(<span class="function"><span class="params">response</span> =&gt;</span> response.arrayBuffer())</span><br><span class="line">    .then(<span class="function"><span class="params">buffer</span> =&gt;</span> WebAssembly.compile(buffer))</span><br><span class="line">    .then(<span class="function"><span class="params">module</span> =&gt;</span> &#123;</span><br><span class="line">      <span class="comment">//针对wasm所需的import处理，importObject</span></span><br><span class="line">      imports.env = imports.env || &#123;&#125;</span><br><span class="line">      imports.env = imports.env || &#123;&#125;</span><br><span class="line">      imports.env.DYNAMICTOP_PTR = imports.env.DYNAMICTOP_PTR || <span class="number">0</span>;</span><br><span class="line">      imports.env.tempDoublePtr = imports.env.tempDoublePtr || <span class="number">0</span>;</span><br><span class="line">      imports.env.ABORT = imports.env.ABORT || <span class="number">0</span>;</span><br><span class="line">      imports.global = imports.global || &#123; <span class="attr">NaN</span>: <span class="number">1</span>, <span class="attr">Infinity</span>: <span class="number">2</span> &#125;;</span><br><span class="line">      imports.env.abortStackOverflow = imports.env.abortStackOverflow || <span class="keyword">new</span> <span class="built_in">Function</span>();</span><br><span class="line">      imports.env.nullFunc_X = imports.env.nullFunc_X || <span class="keyword">new</span> <span class="built_in">Function</span>();</span><br><span class="line">      <span class="comment">// 开辟内存空间</span></span><br><span class="line">      imports.env.memoryBase = imports.env.memoryBase || <span class="number">0</span></span><br><span class="line">      <span class="keyword">if</span> (!imports.env.memory) &#123;</span><br><span class="line">        imports.env.memory = <span class="keyword">new</span> WebAssembly.Memory(&#123; <span class="attr">initial</span>: <span class="number">256</span> &#125;)</span><br><span class="line">      &#125;</span><br><span class="line">      <span class="comment">// 创建变量映射表</span></span><br><span class="line">      imports.env.tableBase = imports.env.tableBase || <span class="number">0</span></span><br><span class="line">      <span class="keyword">if</span> (!imports.env.table) &#123;</span><br><span class="line">        imports.env.table = <span class="keyword">new</span> WebAssembly.Table(&#123; <span class="attr">initial</span>: <span class="number">2</span>, <span class="attr">element</span>: <span class="string">'anyfunc'</span> &#125;)</span><br><span class="line">      &#125;</span><br><span class="line">      <span class="comment">// 创建 WebAssembly 实例</span></span><br><span class="line">      <span class="keyword">return</span> <span class="keyword">new</span> WebAssembly.instantiate(<span class="built_in">module</span>, imports)</span><br><span class="line">    &#125;)</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<h3 id="html片段"><a href="#html片段" class="headerlink" title="html片段"></a>html片段</h3><figure class="highlight html"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br></pre></td><td class="code"><pre><span class="line"><span class="tag">&lt;<span class="name">button</span> <span class="attr">class</span>=<span class="string">"mybutton"</span>&gt;</span>取随机数<span class="tag">&lt;/<span class="name">button</span>&gt;</span></span><br><span class="line">    <span class="tag">&lt;<span class="name">script</span>&gt;</span></span><br><span class="line"><span class="javascript">        <span class="keyword">const</span> wasm = loadWebAssembly(<span class="string">'example.wasm'</span>);</span></span><br><span class="line"><span class="javascript">        <span class="keyword">let</span> myButton = <span class="built_in">document</span>.getElementsByClassName(<span class="string">'mybutton'</span>)[<span class="number">0</span>];</span></span><br><span class="line"><span class="javascript">        <span class="keyword">const</span> x = <span class="number">1.22</span>;</span></span><br><span class="line"><span class="javascript">        <span class="keyword">const</span> y = <span class="number">2.11</span>;</span></span><br><span class="line"><span class="javascript">        myButton.onclick = <span class="function"><span class="keyword">function</span> (<span class="params"></span>) </span>&#123;</span></span><br><span class="line"><span class="javascript">            wasm.then(<span class="function"><span class="params">module</span> =&gt;</span> &#123;</span></span><br><span class="line"><span class="javascript">                <span class="built_in">console</span>.log(<span class="string">'wasm-计算：'</span> + <span class="built_in">module</span>.exports._add(x, y));</span></span><br><span class="line"><span class="javascript">                <span class="built_in">console</span>.log(<span class="string">'js-计算：'</span> + (x + y));</span></span><br><span class="line">            &#125;);</span><br><span class="line">        &#125;</span><br><span class="line">    <span class="tag">&lt;/<span class="name">script</span>&gt;</span></span><br></pre></td></tr></table></figure>

<h2 id="WebAssembly组成部分"><a href="#WebAssembly组成部分" class="headerlink" title="WebAssembly组成部分"></a>WebAssembly组成部分</h2><blockquote>
<p>实际上** WebAssembly **被称为 “模块”，因为使用WebAssembly，”程序”和”库”之间没有区别 - 只有”模块”，每个模块都可以与其他模块绑定和通信，每个模块都可以具有”模块”主功能。</p>
</blockquote>
<h3 id="必选部分"><a href="#必选部分" class="headerlink" title="必选部分"></a>必选部分</h3><ul>
<li>Type：在模块中定义的函数的函数声明和所有引入函数的函数声明。</li>
<li>Function：给出模块中每个函数一个索引。</li>
<li>Code：模块中每个函数的实际函数体。</li>
</ul>
<h3 id="可选部分"><a href="#可选部分" class="headerlink" title="可选部分"></a>可选部分</h3><ul>
<li>Export：使函数、内存、表（tables）、全局变量等对其他 WebAssembly 或 JavaScript 可见，允许动态链接一些分开编译的组件，即 .dll 的WebAssembly 版本。</li>
<li>Import：允许从其他 WebAssembly 或者 JavaScript 中导入指定的函数、内存、表或者全局变量。</li>
<li>Start：当 WebAssembly 模块加载进来的时候，可以自动运行的函数（类似于 main 函数）。</li>
<li>Global：声明模块的全局变量。</li>
<li>Memory：定义模块用到的内存。</li>
<li>Table：使得可以映射到 WebAssembly 模块以外的值，如映射到 JavaScript 的对象。这在间接函数调用时很有用。</li>
<li>Data：初始化导入的或者局部内存。</li>
<li>Element：初始化导入的或者局部的表。</li>
</ul>
<h2 id="遇到的坑"><a href="#遇到的坑" class="headerlink" title="遇到的坑"></a>遇到的坑</h2><h3 id="无法导入环境变量"><a href="#无法导入环境变量" class="headerlink" title="无法导入环境变量"></a>无法导入环境变量</h3><blockquote>
<p>在执行 source ./emsdk_env.sh 命令时失败，无法添加环境变量</p>
</blockquote>
<p>思路：脚本实现不了，就不要使用提供的脚本命令，手动添加也可以。最终是要在任何窗口中都能执行命令。<br>手动添加环境变量，一般都是添加在当前用户区，和windows理念一样。</p>
<figure class="highlight bash"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br></pre></td><td class="code"><pre><span class="line">PATH=<span class="string">"/Library/Frameworks/Python.framework/Versions/3.7/bin:<span class="variable">$&#123;PATH&#125;</span>"</span></span><br><span class="line"><span class="built_in">export</span> PATH=/Users/liuzhipan/emsdk:<span class="variable">$PATH</span></span><br><span class="line"><span class="built_in">export</span> PATH=/Users/liuzhipan/emsdk/clang/e1.38.8_64bit:<span class="variable">$PATH</span></span><br><span class="line"><span class="built_in">export</span> PATH=/Users/liuzhipan/emsdk/node/8.9.1_64bit/bin:<span class="variable">$PATH</span></span><br><span class="line"><span class="built_in">export</span> PATH=/Users/liuzhipan/emsdk/emscripten/1.38.8:<span class="variable">$PATH</span></span><br><span class="line"><span class="built_in">alias</span> python=<span class="string">'/Library/Frameworks/Python.framework/Versions/3.7/bin/python3.7'</span></span><br><span class="line"><span class="built_in">export</span> EMSDK=/Users/liuzhipan/emsdk</span><br><span class="line"><span class="built_in">export</span> EM_CONFIG=/Users/liuzhipan/.emscripten</span><br><span class="line"><span class="built_in">export</span> BINARYEN_ROOT=/Users/liuzhipan/emsdk/clang/e1.38.8_64bit/binaryen</span><br><span class="line"><span class="built_in">export</span> EMSCRIPTEN=/Users/liuzhipan/emsdk/emscripten/1.38.8</span><br><span class="line"><span class="built_in">export</span> PATH=<span class="variable">$PATH</span>:<span class="variable">$EMSDK</span>:<span class="variable">$EM_CONFIG</span>:<span class="variable">$BINARYEN_ROOT</span>:<span class="variable">$EMSCRIPTEN</span></span><br></pre></td></tr></table></figure>

<p>仿照这份环境变量修改对应目录-路径即可。</p>
<blockquote>
<p>vim ~/.bash_profile         //添加上述的环境变量<br>source ~/.bash_profile   // 刷新当前用户环境变量缓冲，使其生效</p>
</blockquote>
<h3 id="实例化module失败"><a href="#实例化module失败" class="headerlink" title="实例化module失败"></a>实例化module失败</h3><blockquote>
<p>构建出来包之后，发现importObject提供的资源缺少导致实例化module失败。</p>
</blockquote>
<p>思路：官网提供的大部分都是env对象</p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">// 开辟内存空间</span></span><br><span class="line">imports.env.memoryBase = imports.env.memoryBase || <span class="number">0</span></span><br><span class="line"><span class="keyword">if</span> (!imports.env.memory) &#123;</span><br><span class="line">    imports.env.memory = <span class="keyword">new</span> WebAssembly.Memory(&#123; <span class="attr">initial</span>: <span class="number">256</span> &#125;)</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">// 创建变量映射表</span></span><br><span class="line">imports.env.tableBase = imports.env.tableBase || <span class="number">0</span></span><br><span class="line"><span class="keyword">if</span> (!imports.env.table) &#123;</span><br><span class="line">    imports.env.table = <span class="keyword">new</span> WebAssembly.Table(&#123; <span class="attr">initial</span>: <span class="number">2</span>, <span class="attr">element</span>: <span class="string">'anyfunc'</span> &#125;)</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>** 问题关键 **</p>
<p>可是我导出来的wasm-module不止这几个。</p>
<figure class="highlight bash"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br></pre></td><td class="code"><pre><span class="line">(import <span class="string">"env"</span> <span class="string">"memory"</span> (memory <span class="variable">$env</span>.memory 256))</span><br><span class="line">(import <span class="string">"env"</span> <span class="string">"table"</span> (table <span class="variable">$env</span>.table 2 anyfunc))</span><br><span class="line">(import <span class="string">"env"</span> <span class="string">"memoryBase"</span> (global <span class="variable">$env</span>.memoryBase i32))</span><br><span class="line">(import <span class="string">"env"</span> <span class="string">"tableBase"</span> (global <span class="variable">$env</span>.tableBase i32))</span><br><span class="line">(import <span class="string">"env"</span> <span class="string">"DYNAMICTOP_PTR"</span> (global <span class="variable">$env</span>.DYNAMICTOP_PTR i32))</span><br><span class="line">(import <span class="string">"env"</span> <span class="string">"tempDoublePtr"</span> (global <span class="variable">$env</span>.tempDoublePtr i32))</span><br><span class="line">(import <span class="string">"env"</span> <span class="string">"ABORT"</span> (global <span class="variable">$env</span>.ABORT i32))</span><br><span class="line">(import <span class="string">"global"</span> <span class="string">"NaN"</span> (global <span class="variable">$global</span>.NaN f64))</span><br><span class="line">(import <span class="string">"global"</span> <span class="string">"Infinity"</span> (global <span class="variable">$global</span>.Infinity f64))</span><br><span class="line">(import <span class="string">"env"</span> <span class="string">"abortStackOverflow"</span> (func <span class="variable">$env</span>.abortStackOverflow (<span class="built_in">type</span> <span class="variable">$t0</span>)))</span><br><span class="line">(import <span class="string">"env"</span> <span class="string">"nullFunc_X"</span> (func <span class="variable">$env</span>.nullFunc_X (<span class="built_in">type</span> <span class="variable">$t0</span>)))</span><br><span class="line">(func <span class="variable">$f2</span> (<span class="built_in">type</span> <span class="variable">$t1</span>) (param <span class="variable">$p0</span> i32) (result i32)</span><br></pre></td></tr></table></figure>

<p>** 处理方案： **</p>
<ul>
<li>所以要对多导出来的资源进行处理。<br>这些都是实例化module需要提供的import.加入对应的字段即可处理！</li>
</ul>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><span class="line">imports.env.DYNAMICTOP_PTR = imports.env.DYNAMICTOP_PTR || <span class="number">0</span>;</span><br><span class="line">imports.env.tempDoublePtr = imports.env.tempDoublePtr || <span class="number">0</span>;</span><br><span class="line">imports.env.ABORT = imports.env.ABORT || <span class="number">0</span>;</span><br><span class="line">imports.global = imports.global || &#123; <span class="attr">NaN</span>: <span class="number">1</span>, <span class="attr">Infinity</span>: <span class="number">2</span> &#125;;</span><br><span class="line">imports.env.abortStackOverflow = imports.env.abortStackOverflow || <span class="keyword">new</span> <span class="built_in">Function</span>();</span><br><span class="line">imports.env.nullFunc_X = imports.env.nullFunc_X || <span class="keyword">new</span> <span class="built_in">Function</span>();</span><br></pre></td></tr></table></figure>

<ul>
<li>还有一种更简洁的。<br>使用wasm-gc去处理。</li>
</ul>

      
    </div>

    
      


    

    
      
    

    
    
    

    

    
      
    
    

    
      <div>
        




  



<ul class="post-copyright">
  <li class="post-copyright-author">
    <strong>本文作者： </strong>修心</li>
  <li class="post-copyright-link">
    <strong>本文链接：</strong>
    
    <a href="https://blog.youngzk.com/posts/7f98c2be/" title="webAssembly">https://blog.youngzk.com/posts/7f98c2be/</a>
  </li>
  <li class="post-copyright-license">
    <strong>版权声明： </strong>本博客所有文章除特别声明外，均采用 <a href="https://creativecommons.org/licenses/by-nc-sa/4.0/zh-CN" rel="noopener" target="_blank"><i class="fa fa-fw fa-creative-commons"></i>BY-NC-SA</a> 许可协议。转载请注明出处！</li>
</ul>

      </div>
    

    <footer class="post-footer">
      
        
          
        
        <div class="post-tags">
          
            <a href="/tags/webAssembly/" rel="tag"># webAssembly</a>
          
        </div>
      

      
      
      

      
        <div class="post-nav">
          <div class="post-nav-next post-nav-item">
            
              <a href="/posts/cf777cb3/" rel="next" title="node-dll 调用">
                <i class="fa fa-chevron-left"></i> node-dll 调用
              </a>
            
          </div>

          <span class="post-nav-divider"></span>

          <div class="post-nav-prev post-nav-item">
            
              <a href="/posts/2a2a7e8a/" rel="prev" title="flutter">
                flutter <i class="fa fa-chevron-right"></i>
              </a>
            
          </div>
        </div>
      

      
      
    </footer>
  </div>
  
  
  
  </article>

  </div>


          </div>
          
  



        </div>
        
          
  
  <div class="sidebar-toggle">
    <div class="sidebar-toggle-line-wrap">
      <span class="sidebar-toggle-line sidebar-toggle-line-first"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-middle"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-last"></span>
    </div>
  </div>

  <aside id="sidebar" class="sidebar">
    <div class="sidebar-inner">

      

      
        <ul class="sidebar-nav motion-element">
          <li class="sidebar-nav-toc sidebar-nav-active" data-target="post-toc-wrap">
            文章目录
          </li>
          <li class="sidebar-nav-overview" data-target="site-overview-wrap">
            站点概览
          </li>
        </ul>
      

      <div class="site-overview-wrap sidebar-panel">
        <div class="site-overview">

          <div class="site-author motion-element" itemprop="author" itemscope itemtype="http://schema.org/Person">
  
    <a href="/">
      <img class="site-author-image" itemprop="image" src="/images/avatar.jpg" alt="修心">
      </a>
  
  <p class="site-author-name" itemprop="name">修心</p>
  <div class="site-description motion-element" itemprop="description">修不被别人影响的心，修不被自己控制的心，修不被别人诱惑的心。</div>
</div>


  <nav class="site-state motion-element">
    
      <div class="site-state-item site-state-posts">
        
          <a href="/archives/">
        
          <span class="site-state-item-count">17</span>
          <span class="site-state-item-name">日志</span>
        </a>
      </div>
    

    
      
      
      <div class="site-state-item site-state-categories">
        
          
            <a href="/categories/">
          
        
        
        
          
        
          
        
          
        
        <span class="site-state-item-count">3</span>
        <span class="site-state-item-name">分类</span>
        </a>
      </div>
    

    
      
      
      <div class="site-state-item site-state-tags">
        
          
            <a href="/tags/">
          
        
        
        
          
        
          
        
          
        
          
        
          
        
          
        
          
        
          
        
          
        
          
        
          
        
          
        
          
        
          
        
          
        
          
        
          
        
          
        
          
        
          
        
        <span class="site-state-item-count">20</span>
        <span class="site-state-item-name">标签</span>
        </a>
      </div>
    
  </nav>







  <div class="links-of-author motion-element">
    
      <span class="links-of-author-item">
      
      
        
      
      
        
      
        <a href="https://github.com/1160007652" title="GitHub &rarr; https://github.com/1160007652" rel="noopener" target="_blank"><i class="fa fa-fw fa-github"></i>GitHub</a>
      </span>
    
      <span class="links-of-author-item">
      
      
        
      
      
        
      
        <a href="mailto:1160007652@qq.com" title="E-Mail &rarr; mailto:1160007652@qq.com" rel="noopener" target="_blank"><i class="fa fa-fw fa-envelope"></i>E-Mail</a>
      </span>
    
  </div>



  <div class="cc-license motion-element" itemprop="license">
  
  
    
  
  
  
    <a href="https://creativecommons.org/licenses/by-nc-sa/4.0/zh-CN" class="cc-opacity" rel="noopener" target="_blank"><img src="/images/cc-by-nc-sa.svg" alt="Creative Commons"></a>
  </div>





          
          
        </div>
      </div>

      
      <!--noindex-->
        <div class="post-toc-wrap motion-element sidebar-panel sidebar-panel-active">
          <div class="post-toc">

            
            
            
            

            
              <div class="post-toc-content"><ol class="nav"><li class="nav-item nav-level-2"><a class="nav-link" href="#What-WebAssembly"><span class="nav-number">1.</span> <span class="nav-text">What WebAssembly ?</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#webAssembly的优势"><span class="nav-number">2.</span> <span class="nav-text">webAssembly的优势</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#开发前准备工作"><span class="nav-number">3.</span> <span class="nav-text">开发前准备工作</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#操作系统"><span class="nav-number">3.1.</span> <span class="nav-text">操作系统</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#安装工具"><span class="nav-number">3.2.</span> <span class="nav-text">安装工具</span></a><ol class="nav-child"><li class="nav-item nav-level-4"><a class="nav-link" href="#git"><span class="nav-number">3.2.1.</span> <span class="nav-text">git</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#node"><span class="nav-number">3.2.2.</span> <span class="nav-text">node</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#python"><span class="nav-number">3.2.3.</span> <span class="nav-text">python</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#cmake"><span class="nav-number">3.2.4.</span> <span class="nav-text">cmake</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#emsdk"><span class="nav-number">3.2.5.</span> <span class="nav-text">emsdk</span></a></li></ol></li><li class="nav-item nav-level-3"><a class="nav-link" href="#浏览器支持"><span class="nav-number">3.3.</span> <span class="nav-text">浏览器支持</span></a></li></ol></li><li class="nav-item nav-level-2"><a class="nav-link" href="#开始编程"><span class="nav-number">4.</span> <span class="nav-text">开始编程</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#编写C代码"><span class="nav-number">4.1.</span> <span class="nav-text">编写C代码</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#编译出wasm"><span class="nav-number">4.2.</span> <span class="nav-text">编译出wasm</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#调用wasm"><span class="nav-number">4.3.</span> <span class="nav-text">调用wasm</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#html片段"><span class="nav-number">4.4.</span> <span class="nav-text">html片段</span></a></li></ol></li><li class="nav-item nav-level-2"><a class="nav-link" href="#WebAssembly组成部分"><span class="nav-number">5.</span> <span class="nav-text">WebAssembly组成部分</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#必选部分"><span class="nav-number">5.1.</span> <span class="nav-text">必选部分</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#可选部分"><span class="nav-number">5.2.</span> <span class="nav-text">可选部分</span></a></li></ol></li><li class="nav-item nav-level-2"><a class="nav-link" href="#遇到的坑"><span class="nav-number">6.</span> <span class="nav-text">遇到的坑</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#无法导入环境变量"><span class="nav-number">6.1.</span> <span class="nav-text">无法导入环境变量</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#实例化module失败"><span class="nav-number">6.2.</span> <span class="nav-text">实例化module失败</span></a></li></ol></li></ol></div>
            

          </div>
        </div>
      <!--/noindex-->
      

      

    </div>
  </aside>
  <div id="sidebar-dimmer"></div>


        
      </div>
    </main>

    <footer id="footer" class="footer">
      <div class="footer-inner">
        <div class="copyright">&copy; 2018 – <span itemprop="copyrightYear">2019</span>
  <span class="with-love" id="animate">
    <i class="fa fa-user"></i>
  </span>
  <span class="author" itemprop="copyrightHolder">修心</span>

  

  
</div>

<div>
  修不被别人影响的心，修不被自己控制的心，修不被别人诱惑的心。
</div>









        
<div class="busuanzi-count">
  <script async src="https://busuanzi.ibruce.info/busuanzi/2.3/busuanzi.pure.mini.js"></script>

  
    <span class="post-meta-item-icon">
      <i class="fa fa-user"></i>
    </span>
    <span class="site-uv" title="总访客量">
      <span class="busuanzi-value" id="busuanzi_value_site_uv"></span>
    </span>
  

  
    <span class="post-meta-divider">|</span>
  

  
    <span class="post-meta-item-icon">
      <i class="fa fa-eye"></i>
    </span>
    <span class="site-pv" title="总访问量">
      <span class="busuanzi-value" id="busuanzi_value_site_pv"></span>
    </span>
  
</div>









        
      </div>
    </footer>

    
      <div class="back-to-top">
        <i class="fa fa-arrow-up"></i>
        
          <span id="scrollpercent"><span>0</span>%</span>
        
      </div>
    

    

    

    

  </div>

  

<script>
  if (Object.prototype.toString.call(window.Promise) !== '[object Function]') {
    window.Promise = null;
  }
</script>






  











  
  









  
  <script src="/lib/jquery/index.js?v=3.4.1"></script>

  
  <script src="/lib/fancybox/source/jquery.fancybox.pack.js"></script>

  
  <script src="/lib/velocity/velocity.min.js?v=1.2.1"></script>

  
  <script src="/lib/velocity/velocity.ui.min.js?v=1.2.1"></script>




  <script src="/js/utils.js?v=7.2.0"></script>

  <script src="/js/motion.js?v=7.2.0"></script>



  
  


  <script src="/js/affix.js?v=7.2.0"></script>

  <script src="/js/schemes/pisces.js?v=7.2.0"></script>



  
  <script src="/js/scrollspy.js?v=7.2.0"></script>
<script src="/js/post-details.js?v=7.2.0"></script>



  <script src="/js/next-boot.js?v=7.2.0"></script>

  

  

  


  













  <script src="/js/local-search.js?v=7.2.0"></script>












<script>
// GET RESPONSIVE HEIGHT PASSED FROM IFRAME

window.addEventListener("message", function(e) {
  var data = e.data;
  if ((typeof data === 'string') && (data.indexOf('ciu_embed') > -1)) {
    var featureID = data.split(':')[1];
    var height = data.split(':')[2];
    $(`iframe[data-feature=${featureID}]`).height(parseInt(height) + 30);
  }
}, false);
</script>








  

<script src="/live2dw/lib/L2Dwidget.min.js?094cbace49a39548bed64abff5988b05"></script><script>L2Dwidget.init({"pluginRootPath":"live2dw/","pluginJsPath":"lib/","pluginModelPath":"assets/","tagMode":false,"debug":false,"model":{"jsonPath":"/live2dw/assets/hijiki.model.json"},"display":{"position":"right","width":150,"height":300},"mobile":{"show":true},"react":{"opacity":0.7},"log":false});</script></body>
</html>
